package com.ruoyi.coal.modules.minio;

import cn.hutool.core.date.DateUtil;
import io.minio.MinioClient;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidArgumentException;
import io.minio.errors.InvalidBucketNameException;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.NoResponseException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

@Configuration
@Service("uploadCloud")
public class MinioConfig {
    private static final Logger log = LoggerFactory.getLogger(com.ruoyi.coal.modules.minio.MinioConfig.class);

    @Resource
    private MinioProperties minioProperties;

    @Bean
    public MinioClient getMinioClient() {
        System.out.println(this.minioProperties.getEndpoint());
        try {
            System.out.println("minio连接");
            return new MinioClient(this.minioProperties.getEndpoint(), this.minioProperties.getAccessKey(), this.minioProperties.getSecretKey());
        } catch (InvalidEndpointException|io.minio.errors.InvalidPortException e) {
            e.printStackTrace();
            log.info("------创建Minio客户端失败------");
            return null;
        }
    }

    public String upload(MultipartFile file, String fileType, String fileDay) throws IOException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, InvalidArgumentException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String date = String.valueOf(calendar.get(1)) + "-" + String.valueOf(calendar.get(2) + 1);
        String result = this.minioProperties.getEndpoint() + "/" + this.minioProperties.getBucketname();
        if (file == null || file.getSize() == 0L || file.isEmpty())
            throw new RuntimeException("上传文件为空，请重新上传");
                    String filename = "";
        if (file.getOriginalFilename() == null || file.getOriginalFilename().equals("")) {
            filename = file.getName();
        } else {
            filename = file.getOriginalFilename();
        }
        assert filename != null;
        String newFilename = fileType + "/" + date + "/" + DateUtil.today() + "/" + fileDay + "_" + filename;
        getMinioClient().putObject(this.minioProperties.getBucketname(), newFilename, file.getInputStream(), Long.valueOf(file.getSize()), null, null, file.getContentType());
        return result + "/" + newFilename;
    }

    public void removeObject(String filename) {
        try {
            getMinioClient().removeObject(this.minioProperties.getBucketname(), filename);
        } catch (Exception e) {
            log.info("文件删除失败"+ e.getMessage());
                    System.out.println("文件删除失败"+ e.getMessage());
        }
    }

    public void downloadImage(String imageUrl, String destinationPath) throws IOException {
        imageUrl = imageUrl.replace("http://127.0.0.1:3000", "http://127.0.0.1:9000");
        URL url = new URL(imageUrl);
        File destinationFile = new File(destinationPath);
        if (destinationFile.exists())
            destinationFile.delete();
        try (InputStream input = url.openStream()) {
            Files.copy(input, destinationFile.toPath(), new CopyOption[] { StandardCopyOption.REPLACE_EXISTING });
        } catch (Exception e) {
            log.info("文件下载失败"+ e.getMessage());
                    System.out.println("文件下载失败"+ e.getMessage());
        }
    }

    public String downloadFile(String urlString, String suffix) throws IOException {
        URL url = new URL(urlString);
        Path tempFile = Files.createTempFile("downloaded-", suffix, (FileAttribute<?>[])new FileAttribute[0]);
        try(InputStream in = new BufferedInputStream(url.openStream());
            FileOutputStream out = new FileOutputStream(tempFile.toFile())) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1)
                out.write(buffer, 0, bytesRead);
            return tempFile.toString();
        } catch (Exception e) {
            log.error("文件下载失败"+ e.getMessage());
            return null;
        }
    }
}

